package com.yxsk.relay.job.admin.web.controller;

import com.yxsk.relay.job.admin.controller.JobExecuteLogController;
import com.yxsk.relay.job.admin.data.entity.JobDetails;
import com.yxsk.relay.job.admin.data.entity.JobExecuteLog;
import com.yxsk.relay.job.admin.data.entity.JobTriggerLog;
import com.yxsk.relay.job.admin.data.service.JobAppsService;
import com.yxsk.relay.job.admin.data.service.JobDetailService;
import com.yxsk.relay.job.admin.data.service.JobExecuteLogService;
import com.yxsk.relay.job.admin.data.service.JobTriggerLogService;
import com.yxsk.relay.job.admin.web.common.data.PageSort;
import com.yxsk.relay.job.admin.web.common.exception.RelayAdminWebRuntimeException;
import com.yxsk.relay.job.component.common.protocol.message.base.ResultResponse;
import com.yxsk.relay.job.component.common.protocol.message.log.query.LogQueryResponseDto;
import com.yxsk.relay.job.component.common.utils.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Map;

/**
 * @Author 11376
 * @CreaTime 2019/7/4 9:14
 * @Description
 */
@Controller
@RequestMapping("/admin/quartz/job/execute")
public class AdminExecuteLogController extends BaseController<JobExecuteLog, JobExecuteLogService> {

    @Autowired
    private JobExecuteLogController logController;
    @Autowired
    private JobAppsService appsService;
    @Autowired
    private JobDetailService jobDetailService;
    @Autowired
    private JobTriggerLogService triggerLogService;

    @GetMapping("")
    public String list(Model model,
                       @RequestParam(value = "appId", required = false) String appId,
                       @RequestParam(value = "jobId", required = false) String jobId,
                       @RequestParam(value = "startTime", required = false) String startTime,
                       @RequestParam(value = "endTime", required = false) String endTime) {
        // 查询应用
        model.addAttribute("apps", this.appsService.findAllNormalEntities());
        // 查询任务
        model.addAttribute("jobs", this.jobDetailService.findAllNormalEntities());

        // 创建分页对象
        PageRequest page = PageSort.nativePageRequest(Sort.Direction.DESC);
        // 查询执行日志
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Page<Map> result;
        try {
            result = this.service.findPageByCondition(appId, jobId, StringUtils.hasLength(startTime) ? dateFormat.parse(startTime) : null, StringUtils.hasLength(endTime) ? dateFormat.parse(endTime) : null, page);
        } catch (ParseException e) {
            throw new RelayAdminWebRuntimeException(e);
        }
        model.addAttribute("list", result.getContent());
        model.addAttribute("page", result);
        return getBasicDir() + "/index";
    }

    @GetMapping("/executeLog/{executeLogId}")
    public String toExecuteLog(@PathVariable("executeLogId") String executeLogId, Model model) {
        try {
            ResultResponse<LogQueryResponseDto> resultResponse = this.logController.query(executeLogId, null, null);
            if (ResultResponse.isOk(resultResponse)) {
                model.addAttribute("data", resultResponse.getData());
            } else {
                model.addAttribute("errorLog", Arrays.asList(new String[]{resultResponse.getMessage()}));
            }
        } catch (Exception e) {
            model.addAttribute("errorLog", Arrays.asList(ExceptionUtils.getStackInfo(e).split("\\r?\\n")));
        }
        model.addAttribute("executeLogId", executeLogId);
        return getBasicDir() + "/logDetail";
    }

    @GetMapping("/info/{id}")
    public String info(@PathVariable("id") String id, Model model) {
        // 查询执行记录
        JobExecuteLog executeLog = this.service.findById(id);
        model.addAttribute("execute", executeLog);
        if (executeLog != null) {
            JobTriggerLog triggerLog = this.triggerLogService.findById(executeLog.getTriggerLogId());
            model.addAttribute("trigger", triggerLog);
            if (triggerLog != null) {
                JobDetails jobDetails = this.jobDetailService.findById(triggerLog.getJobId());
                model.addAttribute("job", jobDetails);
                if (jobDetails != null) {
                    model.addAttribute("app", this.appsService.findById(jobDetails.getAppId()));
                }
            }
        }
        return getBasicDir() + "/infoDetail";
    }

    @Override
    protected String getBasicDir() {
        return "/system/job/execute";
    }
}
